<template>
    <div class="order-template-add">
        <el-form :model="form.param" label-width="auto" :rules="innerrule" ref="formRef">
            <div class="form-content">
                <el-form-item label="模板名称" prop="name"
                    ><el-input
                        v-model.trim="form.param.name"
                        maxlength="20"
                        show-word-limit
                        class="w420"
                        placeholder="请输入模板名称"></el-input
                ></el-form-item>
                <el-form-item label="说明"
                    ><el-input
                        v-model.trim="form.param.description"
                        maxlength="100"
                        show-word-limit
                        type="textarea"
                        class="w420"
                        placeholder="请输入说明"
                        resize="none"></el-input
                ></el-form-item>
                <el-form-item label="起送价" prop="goodsFreightFee"
                    ><div>
                        满&nbsp;<el-input
                            placeholder="请输入"
                            v-model="form.param.goodsFreightFee"
                            class="space w100"></el-input
                        ><span>&nbsp;元 </span>
                    </div>
                </el-form-item>
                <el-form-item class="custom-form-item" label="">
                    <span>未配置运费地区，默认不可购买及配送</span>
                    <div class="content" v-for="(item, index) in form.param.area" :key="index">
                        <div class="square">
                            <div class="items">
                                <el-form :model="item" :rules="innerrule" ref="ruleFormRef">
                                    <el-form-item
                                        label="地区"
                                        :required="false"
                                        prop="areaInner"
                                        style="margin-bottom: 22px">
                                        <el-cascader
                                            class="w400"
                                            :options="item.placeOptions"
                                            :props="placeProps"
                                            v-model="item.areaInner"
                                            clearable
                                            collapse-tags
                                            collapse-tags-tooltip
                                            @change="
                                                () => {
                                                    selectPlace(item.areaInner, index);
                                                }
                                            " />
                                    </el-form-item>
                                    <el-row style="margin-bottom: 22px">
                                        <el-col :span="10">
                                            <el-form-item label="运费" prop="freightFee" class="custom-small-form-item">
                                                <el-input
                                                    placeholder="请输入"
                                                    v-model="item.freightFee"
                                                    class="right w100"></el-input
                                                >元
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24" class="order-col">
                                            <!-- todo:选中 -->
                                            <el-checkbox
                                                @change="handleCheckboxChange($event, index)"
                                                v-model="item.isFreeFreightFee"
                                                style="margin-right: 12px"></el-checkbox>
                                            <el-form-item
                                                prop="freeFreightFee"
                                                label="订单满"
                                                :rules="freeFreightFeeRules(item.isFreeFreightFee)"
                                                class="custom-small-form-item">
                                                <el-input
                                                    :disabled="!item.isFreeFreightFee"
                                                    placeholder="请输入"
                                                    v-model="item.freeFreightFee"
                                                    class="right w100"></el-input
                                                >元，免运费
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </div>
                        </div>
                        <img src="@/assets/imgs/logo/del.png" class="img" @click="delRow(index)" v-if="index" />
                        <img src="@/assets/imgs/logo/add.png" class="img" @click="addRow" />
                    </div>
                </el-form-item>
            </div>
            <div class="form-footer" style="flex: auto">
                <div>
                    <el-button @click="cancelHandler()">取消</el-button>
                    <el-button type="primary" @click="submit(formRef)">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { reactive, ref, unref, watch, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/request';
import storage from '@/commons/storage';
import { cloneDeep, isEmpty, isNotEmpty } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import { debounce } from 'lodash';

const router = useRouter();
const route = useRoute();

const props = defineProps(['open', 'formData']);
const ruleFormRef = ref();
const formRef = ref();
const emit = defineEmits(['close', 'submit']);
const delIds = ref([]);
let selectPlaceIds = ref([]);
const editParam = ref({});
const show = computed(() => {
    return props.open;
});
const form = reactive({
    param: {
        shopId: '',
        name: '',
        description: '',
        goodsFreightFee: '',
        area: [
            {
                isFreeFreightFee: false,
                freightFee: '',
                freeFreightFee: '',
                blockSort: 1,
                areaInner: []
            }
        ]
    },
    allList: []
});
// 校验规则
const innerrule = reactive({
    freightFee: [
        { required: true, message: '运费不能为空' },
        {
            pattern: /^\d{0,9}(\.\d{0,2})?$/,
            message: '请输入小于9位数的正数，最多保留2位小数'
        }
    ],
    // freeFreightFee: [
    //     { message: '免运费不能为空', trigger: 'blur' },
    //     {
    //         pattern: /^\d{0,9}(\.\d{0,2})?$/,
    //         message: '请输入小于9位数的正数，最多保留2位小数'
    //     }
    // ],
    name: [{ required: true, message: '模板名称不能为空' }],
    areaInner: [{ required: true, message: '地区不能为空' }],
    goodsFreightFee: [
        { required: true, message: '起送价不能为空' },
        {
            pattern: /^\d{0,9}(\.\d{0,2})?$/,
            message: '请输入小于9位数的正数，最多保留2位小数'
        }
    ]
});
const skuListValidate = callback => {
    let list = [];
    ruleFormRef.value.map(el => {
        let p = new Promise(function (resolve, reject) {
            el.validate(i => {
                if (i) {
                    resolve();
                } else {
                    reject();
                }
            });
        });
        list.push(p);
    });
    Promise.all(list)
        .then(() => {
            callback();
        })
        .catch(err => {});
};
const freeFreightFeeRules = required => {
    return [
        {
            required: required,
            message: '免运费不能为空',
            trigger: 'blur'
        },
        {
            pattern: /^\d{0,9}(\.\d{0,2})?$/,
            message: '请输入小于9位数的正数，最多保留2位小数'
        }
    ];
};
const placeProps = {
    multiple: true,
    checkStrictly: false,
    value: 'id',
    label: 'name'
};
let placeOptions = ref([]);

/**
 * 取消
 */
const cancelHandler = () => {
    // router.push({ path: '/marketing/group' });
    router.back();
};

/**
 * 提交保存
 * @param {*} tableRef
 */
const submit = debounce(async tableRef => {
    if (!tableRef) return;
    await tableRef.validate((valid, fields) => {
        if (valid) {
            skuListValidate(() => {
                if (form.param.templateId) {
                    const params = JSON.parse(JSON.stringify(form.param));
                    params.shopId = storage.get('ZW-SHOPID');
                    params.goodsFreightFee = parseInt(params.goodsFreightFee * 100); //起送价元转分
                    //编辑运费模板
                    const placeData = [];
                    params.area.map((item, indexs) => {
                        const data = [];
                        item.areaInner.map((value, index) => {
                            const content = {
                                id: '',
                                freightFee: '',
                                freeFreightFee: '',
                                provinceId: '',
                                cityId: '',
                                areaId: '',
                                blockSort: 1
                            };
                            content.freeFreightFee = parseInt(item.freeFreightFee * 100);
                            content.freightFee = parseInt(item.freightFee * 100);
                            content.blockSort = indexs + 1;
                            if (item.id) {
                                content.id = item.id[index];
                            } else {
                                delete content.id;
                            }
                            content.provinceId = value[0];
                            content.cityId = value[1] ? value[1] : '';
                            content.areaId = value[2] ? value[2] : '';
                            data.push(content);
                        });
                        placeData.push(data);
                    });
                    params.area = placeData;
                    const placeDataClone = (placeData || [])?.flat()?.map(item => item.id);
                    const deletedAreaIds = areaIdsClone.filter(item => !placeDataClone.find(fitem => item == fitem));
                    request('editfreight', {
                        ...params,
                        templateId: form.param.templateId,
                        deletedAreaId: deletedAreaIds
                    }).then(res => {
                        ElMessage.success('编辑成功');
                        cancelHandler();
                    });
                } else {
                    //新增运费模板
                    const params = JSON.parse(JSON.stringify(form.param));
                    params.shopId = storage.get('ZW-SHOPID');
                    params.goodsFreightFee = parseInt(params.goodsFreightFee * 100); //起送价元转分
                    params.area.map(item => {
                        item.freeFreightFee = parseInt(item.freeFreightFee * 100);
                        item.freightFee = parseInt(item.freightFee * 100);
                        var arrPlace = [];
                        item.areaInner.map(value => {
                            var placeParam = {
                                provinceId: '',
                                cityId: '',
                                areaId: ''
                            };
                            value.map((id, index) => {
                                if (index == 0) {
                                    placeParam.provinceId = id;
                                } else if (index == 1) {
                                    placeParam.cityId = id;
                                } else {
                                    placeParam.areaId = id;
                                }
                            });
                            arrPlace.push(placeParam);
                        });
                        item.areaInner = arrPlace;
                    });
                    request('addfreight', params).then(res => {
                        ElMessage.success('创建成功');
                        cancelHandler();
                    });
                }
            });
        }
    });
}, 400);
/**
 * 获取地区列表
 */
const getPlace = () => {
    request('regionServ', { level: 2 }).then(res => {
        placeOptions.value = res.data;
        setFormParamAreaPlaceOptions();
    });
};
getPlace();

/**
 * 实时记录当前被选中的城市ID
 * @param {*} cur
 * @param {*} index
 */
const selectedPlaceIds = (cur, index) => {
    const resIdx = selectPlaceIds.value.findIndex(item => item.index === index);
    const resArr = [].concat.apply([], cur);
    if (resIdx > -1) {
        selectPlaceIds.value[resIdx].value = resArr;
    } else {
        const spid = {
            index,
            value: resArr
        };
        selectPlaceIds.value.push(spid);
    }
};

/**
 * 为form.param.area的元素注入placeOptions属性
 * 如果index不为空，则为原placeOptions判断disabled属性
 * @param {*} index
 */
const setFormParamAreaPlaceOptions = (index, type = 'all') => {
    if (type === 'all') {
        form.param.area.map((item, idx) => {
            if (isEmpty(index) || idx !== index) {
                item.placeOptions = getNewPlaceOptions(idx);
            }
        });
    } else {
        form.param.area[index].placeOptions = getNewPlaceOptions();
    }
};

/**
 * 创建PlaceOptions
 * @param {*} index
 */
const getNewPlaceOptions = index => {
    const currentPlaceOptions = cloneDeep(placeOptions.value);
    const notSelfSelectedPlaceIds = getNotSelfSelectedPlaceIds(index);
    const iteratePlaceOptions = list => {
        for (const item of list) {
            if (isNotEmpty(notSelfSelectedPlaceIds) && notSelfSelectedPlaceIds.indexOf(item.id) > -1) {
                item.disabled = true;
            } else {
                item.disabled = false;
            }

            if (item.children && item.children.length > 0) {
                iteratePlaceOptions(item.children);
            } else {
                continue;
            }
        }
    };

    iteratePlaceOptions(currentPlaceOptions);
    return cloneDeep(currentPlaceOptions);
};

/**
 * 查询除自己之外所有被选中的城市
 * @param {*} index
 */
const getNotSelfSelectedPlaceIds = index => {
    let result = [];
    selectPlaceIds.value.map((item, idx) => {
        if (isNotEmpty(index) && index !== idx) {
            result.push(...item.value);
            return;
        }
        if (isEmpty(index)) {
            result.push(...item.value);
            return;
        }
    });
    result = Array.from(new Set(result));
    const temp = [];
    placeOptions.value.map(item => {
        result.map((res, idx) => {
            if (item.id === res) {
                const r = item.children.some(i => result.indexOf(i.id) === -1);
                if (r) {
                    temp.push(idx);
                }
            }
        });
    });
    const ret = [];
    result.map((item, idx) => {
        if (!temp.includes(idx)) {
            ret.push(item);
        }
    });
    return ret;
};

/**
 * 选择地区操作
 * @param {*} cur
 * @param {*} index
 */
const selectPlace = (cur, index) => {
    // 实时更新已选中的区域ID和城市被选择状态
    selectedPlaceIds(cur, index);
    setFormParamAreaPlaceOptions(index);

    editParam.value = JSON.parse(JSON.stringify(form.param));
    if (editParam.value.templateId) {
        const curData = [];
        const preData = [];
        cur.map(value => {
            curData.push(value.toString());
        });
        form.allList[index].areaInner.map((value, indexs) => {
            preData.push(value.toString());
        });
        preData.forEach((item, indexs) => {
            if (curData.indexOf(item) == -1) {
                if (form.param.area[index].id) {
                    delIds.value.push(editParam.value.area[index].id[indexs]);
                    form.param.area[index].id.splice(indexs, 1);
                }
            }
        });
        if (!cur.length) {
            delete form.param.area[index].id;
        }
    }
};

/**
 * 为form.param.area.placeOptions赋值
 * @param {*} index
 */
const setPlaceOptions = index => {
    const currentPlaceOptions = cloneDeep(placeOptions.value);

    const iteratePlaceOptions = list => {
        for (const item of list) {
            if (selectPlaceIds.value.indexOf(item.id) > -1) {
                item.disabled = true;
            } else {
                item.disabled = false;
            }
            if (item.children && item.children.length > 0) {
                iteratePlaceOptions(item.children);
            } else {
                continue;
            }
        }
    };

    iteratePlaceOptions(currentPlaceOptions);
    form.param.area[index].options = currentPlaceOptions;
};

/**
 * 修改回显或删除操作重新计算已选区域
 */
const resetSelectedPlaceIds = () => {
    form.param.area.map((item, index) => {
        selectedPlaceIds(item.areaInner, index);
    });
    setFormParamAreaPlaceOptions();
};

/**
 * 添加运送区域
 */
const addRow = () => {
    form.param.area.push({
        freightFee: '',
        freeFreightFee: '',
        blockSort: '',
        areaInner: []
    });
    form.allList.push({
        freightFee: '',
        freeFreightFee: '',
        blockSort: '',
        areaInner: []
    });
    const lastIndex = form.param.area.length - 1;
    form.param.area[lastIndex].blockSort = form.param.area.length;
    setFormParamAreaPlaceOptions(lastIndex, 'one');
};

/**
 * 删除运送区域
 * @param {*} index
 */
const delRow = index => {
    if (form.param.templateId) {
        delIds.value = delIds.value.concat(form.param.area[index].id);
    }
    form.param.area.splice(index, 1);
    form.allList.splice(index, 1);
    const resIdx = selectPlaceIds.value.findIndex(item => item.index === index);
    if (resIdx > -1) {
        selectPlaceIds.value.splice(resIdx, 1);
    }
    setFormParamAreaPlaceOptions();
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

let areaIdsClone = reactive([]);
const getDetail = () => {
    request('getfreightDetail', { shopId: storage.get('ZW-SHOPID'), templateId: route.query.id }).then(res => {
        res.data.goodsFreightFee = res.data.goodsFreightFee / 100; //分转元
        if (!Object.getOwnPropertyNames(res.data.area).length) {
            res.data.area = [
                {
                    freightFee: '',
                    freeFreightFee: '',
                    blockSort: 1,
                    areaInner: []
                }
            ];
        } else {
            const area = [];
            Object.getOwnPropertyNames(res.data.area).forEach(key => {
                const innerData = { freeFreightFee: '', freightFee: '', id: [], areaInner: [] };
                res.data.area[key].map((item, index) => {
                    const placeId = [];
                    if (index == 0) {
                        //分转元
                        innerData.freeFreightFee = item.freeFreightFee / 100;
                        innerData.freightFee = item.freightFee / 100;
                    }
                    innerData.id.push(item.id);
                    if (item.provinceId) {
                        placeId.push(item.provinceId);
                    }
                    if (item.cityId) {
                        placeId.push(item.cityId);
                    }

                    if (item.areaId) {
                        placeId.push(item.areaId);
                    }
                    innerData.areaInner.push(placeId);
                });
                area.push(innerData);
            });
            res.data.area = area;
            areaIdsClone.length = 0;
            // areaIdsClone = area.map(item => item.id);
            areaIdsClone = (area || []).map(item => item.id || [])?.flat();
            delete res.data.id;
        }
        form.param = { ...res.data, templateId: route.query.id };
        form.allList = (res?.data?.area || []).map(item => {
            item.isFreeFreightFee = !!item.freeFreightFee;
            item.freeFreightFee = item.freeFreightFee || null;
            return item;
        });
        resetSelectedPlaceIds();
    });
};

const handleCheckboxChange = (val, index) => {
    form.param.area[index].freeFreightFee = null;
    setTimeout(() => {
        if (!val) {
            skuListValidate();
        }
    });
};

/**
 * 修改操作数据回显
 */
// watch(
//     () => props.formData,
//     val => {
//         form.param = JSON.parse(JSON.stringify(val));
//         form.allList = JSON.parse(JSON.stringify(val.area));
//         resetSelectedPlaceIds();
//     },
//     { deep: true }
// );

watch(
    () => route.query.id,
    val => {
        form.param.templateId = val;
        if (val) {
            getDetail();
        }
    },
    {
        immediate: true
    }
);

onMounted(() => {
    // getDetail();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
.order-template-add {
    .custom-form-item {
        .el-form-item__label-wrap {
            margin-left: 0 !important;
        }
        & > .el-form-item__content {
            margin-left: auto;
            flex-direction: column;
            align-items: flex-start;
        }
    }
    .custom-small-form-item {
        .el-form-item__content {
            flex-wrap: nowrap;
        }
    }
    .w400 {
        width: 400px !important;
    }
    .order-col {
        padding-left: 50px;
        display: flex;
    }
}
</style>
<style lang="scss" scoped src="./add.scss"></style>
